import { applyDecorators, UseInterceptors, MethodNotAllowedException } from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';
import { MulterOptions } from '@nestjs/platform-express/multer/interfaces/multer-options.interface';

// 文件上传
export function Upload(filed = 'file', options: MulterOptions) {
  return applyDecorators(UseInterceptors(FileInterceptor(filed, options)));
}

export function fileFilter(type = 'image') {
  return (req: any, file: Express.Multer.File, callback: (error: Error | null, acceptFile: boolean) => void) => {
    // console.log('文件类型', file.mimetype);
    // 文件类型错误
    if (!file.mimetype.includes(type)) {
      callback(new MethodNotAllowedException('文件类型错误'), false);
    } else {
      callback(null, true); //通过
    }
  };
}

export function ImgUpload() {
  return Upload('file', {
    limits: {
      fileSize: Math.pow(1024, 2) * 2,
    },
    fileFilter: fileFilter(),
  });
}

export function TextUpload() {
  return Upload('file', {
    limits: {
      fileSize: Math.pow(1024, 2) * 2,
    },
    fileFilter: fileFilter('text'),
  });
}
